<template>
  <div class="sku">
    <h2>规格预览</h2>
    <el-form :model="formData"
             ref="formData"
             label-width="120px"
             label-position="right">
      <p>已选规格：{{ this.selectedOptionsName }}</p>
      <p>已选路径：{{ this.selectedOptionsSymbol }}</p>
      <p>价格：{{ this.price }} * {{ this.count }}</p>
      <p>说明：{{ this.remark }}</p>
      <p>数量：{{ this.count }}</p>
      <!--规格列表-->
      <div v-for="(title, index) in titles"
           :key="title.index"
           class="item">
        <el-row v-if="index == 1 && isCommon">
          <el-col :span="2"
                  class="title">
            <div>播出时间: </div>
          </el-col>
          <el-col :span="15">
            <!--常规刊例播放时长-->
            <el-checkbox-group v-model="checkboxGroup"
                               @change="timePointChangeHandler">
              <el-checkbox v-for="timePoint in selectedTimePoints"
                           size="medium"
                           :label="timePoint"
                           :key="timePoint">{{timePoint}}</el-checkbox>
            </el-checkbox-group>
          </el-col>
        </el-row>
        <el-row>
          <!--规格名称-->
          <el-col :span="2"
                  class="title">
            <div>{{ title }} :</div>
          </el-col>
          <el-col :span="15">
            <el-tooltip v-for="(symbol, name) in keys[title]"
                        :key="name.index"
                        class="item"
                        effect="dark"
                        :content="name"
                        placement="bottom-end">
              <span :class="{active: active[title] === name, disabled: !canClick(symbol, name, title)}"
                    @click="optionClickHandler(symbol, name, title)">
                {{ name }} &nbsp;&nbsp;({{ symbol }})&nbsp;&nbsp;
              </span>
            </el-tooltip>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'sku',
  components: {},
  mounted() {
    this.$nextTick(function() {
      // 默认选中第一列
      if (typeof this.paths === 'object') {
        for (const path in this.paths) {
          for (let i = 0; i < this.paths[path].values.length; i++) {
            this.optionClickHandler(
              this.paths[path].symbols[i],
              this.paths[path].values[i],
              this.paths[path].titles[i]
            )
          }
          break
        }
      }
    })
  },
  props: {
    titles: {
      // 规格名称
      Array,
      required: true,
      default: [] // ['颜色', '内存', '运营商']
    },
    options: {
      // 规格
      Array,
      required: true,
      default: [] // ['白色', '黑色', '金色'],['128g', '64g', '32g', '16g'],['电信', '联通', '移动']
    },
    keys: {
      Array,
      required: true,
      default: {} // 以规格名称为key: {"颜色":{"白色":0,"黑色":1,"金色":2},"内存":{"128g":3,"64g":4,"32g":5,"16g":6},"运营商":{"电信":7,"联通":8,"移动":9}}
    },
    paths: {
      Array,
      required: true,
      default: {} // 以路径为key: {"0,3,7":{"stock":1,"price":1,"symbols":[0,3,7],"values":["白色","128g","电信"],"titles":["颜色","内存","运营商"]}
    },
    timeSlot: {
      // 段位
      Array,
      default: []
    },
    timePoints: {
      // 播出时间
      Array,
      default: {}
    },
    isCommon: {
      // 是否常规刊例
      Boolean,
      default: false
    }
  },
  data() {
    return {
      // 分隔符默认逗号
      SKU_SEP: ',',
      // 选中的规格
      active: {},
      // 选中的规格用 + 连接字符串
      selectedOptionsName: '',
      // 选中的路径用 ，连接字符串
      selectedOptionsSymbol: '',
      // 选中规格数组
      selectedOptionsArray: [],
      // 路径数组
      selectedOptionsSymbolArray: [],
      // 选中的播出时间
      selectedTimePoints: [],
      // 播出时间checkgroup
      checkboxGroup: [],
      // 选中的播出时间数量
      count: 0,
      // 价格范围
      price: '',
      // 说明
      remark: '',
      // 表单
      formData: {}
    }
  },
  created() {},
  watch: {
    timePoints(value) {}
  },
  methods: {
    getPath(selIds) {
      // 组合选择的属性symbol路径
      return selIds.sort().join(this.SKU_SEP)
    },
    optionClickHandler(symbol, name, title) {
      // 规格toggle操作
      this.active[title] = this.active[title] === name ? null : name
      const selectedTimeSlot = this.active[title]
      if (this.isCommon) {
        // 常规刊例显示播出时间
        if (this.timeSlot.indexOf(selectedTimeSlot) >= 0) {
          this.selectedTimePoints = this.timePoints[selectedTimeSlot]
          this.checkList = this.timePoints[selectedTimeSlot]
          // console.debug('optionClickHandler: %s', selectedTimeSlot)
          // console.debug('optionClickHandler: %s', this.isCommon)
          // console.debug('optionClickHandler: %s', this.selectedTimePoints)
        }
      }
      this.updateSelectedOptions()
      this.updatePrice()
    },
    updateSelectedOptions() {
      // 更新显示选中的规格串, 路径
      this.selectedOptionsArray = []
      this.selectedOptionsSymbolArray = []
      for (let i = 0; i < this.titles.length; i++) {
        const title = this.titles[i]
        const item = this.active[title]
        if (typeof item !== 'undefined' && item != null) {
          this.selectedOptionsArray.push(item)
          this.selectedOptionsSymbolArray.push(this.keys[title][item])
        }
      }
      this.selectedOptionsName = this.selectedOptionsArray.join(' + ')
      this.selectedOptionsSymbol = this.selectedOptionsSymbolArray.join(',')
      // console.debug('optionClickHandler: %s', this.selectedOptionsName)
    },
    updatePrice() {
      const skus = this.skus()
      const obj = skus[this.selectedOptionsSymbol]
      const prices = obj && obj.prices
      const remark = obj && obj.remark
      if (prices) {
        const maxPrice = Math.max.apply(Math, prices)
        const minPrice = Math.min.apply(Math, prices)
        this.price = maxPrice > minPrice ? minPrice + '-' + maxPrice : maxPrice
      } else {
        this.price = '没有设定此规格商品'
      }
      this.price = String(this.price) === 'NaN' ? '未设定价格' : this.price
      this.remark = remark ? remark : ''
      // console.debug('updatePrice: price: %s remark: %s', this.price, remark)
    },
    canClick(symbol, name, title) {
      // console.debug(this.selectedOptionsSymbolArray)
      // 如果元素本身已选中， 则可以点击（让用户取消选择）
      if (this.selectedOptionsSymbolArray.indexOf(symbol) !== -1) return true
      const self = this
      // 过滤已选中的当前选项层的所有属性值的symbol的集合
      const notSiblingsSelIds = this.selectedOptionsSymbolArray
        .filter(v => v !== symbol)
        .filter(v => Object.values(self.keys[title]).indexOf(v) === -1)
      const skus = this.skus()
      const sku = skus[this.getPath(notSiblingsSelIds.concat(symbol))]
      return sku && sku.stock > 0
    },
    timePointChangeHandler(valueArray) {
      // console.debug('timePointChangeHandler %s', value)
      this.count = valueArray.length
      this.price = this.price
    },
    skus() {
      // 生成路径笛卡尔积
      // console.log('sku_computed')
      /* eslint-disable */
      let res = {},
        addRes = (k, s) => {
          // if (res[k]) (res[k].stock += s.stock), res[k].prices.push(s.price)
          // else res[k] = { stock: s.stock, prices: [s.price] }
          res[k] = { stock: s.stock, remark: s.remark, prices: [s.price] }
        },
        combine = (skas, n, s) => {
          let len = skas.length
          skas.forEach((key, i) => {
            for (let j = i + 1; j < len; ++j)
              if (j + n <= len) {
                let tmp = skas.slice(j, j + n),
                  gk = this.getPath(tmp.concat(key))
                addRes(gk, s)
              }
          })
        },
        keys = Object.keys(this.paths)
      for (let key of keys) {
        let s = this.paths[key]
        let skas = key.split(this.SKU_SEP).sort()
        let len = skas.length
        for (let j = 0; j < len; ++j) {
          addRes(skas[j], s)
          j > 0 && j < len - 1 && combine(skas, j, s)
        }
        res[this.getPath(key.split(this.SKU_SEP))] = {
          stock: s.stock,
          remark: s.remark,
          prices: [s.price]
        }
      }
      // console.log('skus:' + res)
      return res
    }
  }
}
</script>

<style lang="css" scoped>
.sku {
  width: 800px;
  height: 700px;
  margin: 0 auto;
  text-align: left;
}
.item {
  width: 100%;
}
.item .title {
  margin-top: 10px;
  text-align: left;
}
.item span {
  display: inline-block;
  width: 100px;
  text-align: center;
  word-break: keep-all; /* 不换行 */
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 内容超出宽度时隐藏超出部分的内容 */
  text-overflow: ellipsis; /* 当对象内文本溢出时显示省略标记(...) ；需与overflow:hidden;一起使用。*/
  border: 2px solid #000;
  margin: 5px;
  padding: 3px 5px;
  cursor: pointer;
}
.item span.active {
  border-color: red;
  color: red;
}
.item span.disabled {
  border: 2px dashed #ccc;
  color: #ccc;
}
.el-checkbox-group {
  margin: 10px 10px 10px 10px;
}
</style>
